﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Forest.Cat.Admin.Models;
using Forest.Cat.Domain.Entities;
using Forest.Cat.Admin.Models.JobHunting;
using Forest.Core;
using Forest.Cat.Domain.Services.JobHunting;
using Forest.Cat.Domain;
using Forest.Cat.Domain.Services.Applications;
using Forest.Cat.Domain.Services.Compnaies;
using Forest.Cat.Domain.Services;
using Forest.Cat.Admin.Models.Applications;
using Forest.Cat.Admin.Extensions;
using Forest.Cat.Domain.Configuration;
using Forest.Cat.Domain.Services.Messages;
using Forest.Cat.Domain.Shared;
using Forest.Cat.Domain.Services.Catalog;

namespace Forest.Cat.Admin.Controllers
{
    public class JobHuntingController : Controller
    {
        #region Fields
        private const int _pageSize = 10;
        private readonly IJobAlertService _jobAlertService;
        private readonly IWorkContext _workcontext;
        private readonly IApplicationService _applicationService;
        private readonly ICompanyService _companyService;
        private readonly IResumeService _resumeService;
        private readonly ISavedJobService _savedJobService;
        private readonly ISavedCompanyService _savedCompanyService;
        private readonly ILovService _lovService;
        private readonly IReceivedMessageService _receivedMessageService;
        private readonly IJobPositionService _jobPositionService;
        #endregion

        #region Ctor
        public JobHuntingController(IJobAlertService jobAlertService, IWorkContext workcontext, IApplicationService applicationService,
            ICompanyService companyService, IResumeService resumeService, ISavedJobService savedJobService,
            ISavedCompanyService savedCompanyService, ILovService lovService, IReceivedMessageService receivedMessageService,
            IJobPositionService jobPositionService)
        {
            _jobAlertService = jobAlertService;
            this._applicationService = applicationService;
            this._workcontext = workcontext;
            this._companyService = companyService;
            this._resumeService = resumeService;
            this._savedJobService = savedJobService;
            this._savedCompanyService = savedCompanyService;
            this._lovService = lovService;
            this._receivedMessageService = receivedMessageService;
            this._jobPositionService = jobPositionService;
        }
        #endregion

        #region 职位订阅
        public ActionResult SavedSearchManage(PagingFilteringModel command)
        {
            if (command.PageSize <= 0) command.PageSize = _pageSize;
            if (command.PageNumber <= 0) command.PageNumber = 1;

            var jobAlertList = _jobAlertService.GetAllJobAlertsByJobseekerId(_workcontext.CurrentUser.Id);
            var searchList = jobAlertList.Select(s => new JobAlertModel()
            {
                Id = s.Id,
                DateCreated = s.DateCreated,
                LastUpdated = s.LastUpdated,
                Frequency = s.Frequency,
                Name = s.Name,
            }).ToList();
            searchList.ForEach(s =>
                {
                    s.FrequencyName = s.Frequency.HasValue ? _lovService.GetLovName(s.Frequency.Value) : string.Empty;
                });
            var model = new JobAlertListModel()
            {
                JobAlertList = new PagedList<JobAlertModel>(searchList, command.PageNumber - 1, _pageSize),
                SearchCount = jobAlertList.Count(),
                PagingFilteringContext = new PagingFilteringModel()
            };
            model.PagingFilteringContext.LoadPagedList(model.JobAlertList);
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SavedSearchEdit(JobAlertModel model)
        {
            if (ModelState.IsValid)
            {
                bool insert = false;

                var entity = _jobAlertService.GetJobAlertById(model.Id);
                if (entity == null)
                {
                    insert = true;
                    entity = new JobAlert();
                    entity.DateCreated = DateTime.Now;
                    entity.Id = Guid.NewGuid();
                    entity.JobseekerId = _workcontext.CurrentUser.Id;
                }
                entity.EducationLevel = model.EducationLevel;
                entity.CategoryCode1 = model.Categories;
                entity.CompanyType = model.CompanyType;
                entity.Deliveries = model.Deliveries;
                entity.Frequency = model.Frequency;
                entity.IndustryCode = model.Industry;
                entity.IsRecommended = model.IsRecommended;
                if (!string.IsNullOrWhiteSpace(model.JobTypeString))
                {
                    entity.JobType = int.Parse(model.JobTypeString);
                }
                if (!string.IsNullOrWhiteSpace(model.PostedDurationString))
                {
                    entity.PostedDuration = int.Parse(model.PostedDurationString);
                }
                entity.Name = model.Name;
                entity.SalaryRange = model.SalaryRange;
                entity.YearsOfService = model.YearsOfService;
                entity.LastUpdated = DateTime.Now;
                if (insert)
                {
                    _jobAlertService.InsertJobAlert(entity);
                }
                else
                {
                    _jobAlertService.UpdateJobAlert(entity);
                }
                return Redirect(Url.Action("SavedSearchManage"));
            }
            SetSavedSearchEditDropDownList(model);
            return View(model);
        }

        public ViewResult SavedSearchAdd()
        {
            var model = new JobAlertModel();

            // 采番
            model.Id = Guid.NewGuid(); ;
            SetSavedSearchEditDropDownList(model);
            return View("SavedSearchEdit", model);
        }

        public ActionResult SavedSearchEdit(Guid? id)
        {
            var model = new JobAlertModel();
            if (id.HasValue)
            {
                var entity = _jobAlertService.GetJobAlertById(id.Value);

                model = new JobAlertModel()
                {
                    Categories = entity.CategoryCode1,
                    CompanyType = entity.CompanyType,
                    Deliveries = entity.Deliveries,
                    EducationLevel = entity.EducationLevel,
                    Frequency = entity.Frequency,
                    Id = entity.Id,
                    Industry = entity.IndustryCode,
                    IsRecommended = entity.IsRecommended ?? false,
                    JobType = entity.JobType,
                    Name = entity.Name,
                    PostedDuration = entity.PostedDuration,
                    SalaryRange = entity.SalaryRange,
                    YearsOfService = entity.YearsOfService,
                    JobTypeString = Convert.ToString(entity.JobType),
                    PostedDurationString = Convert.ToString(entity.PostedDuration)
                };
            }
            SetSavedSearchEditDropDownList(model);
            return View(model);
        }

        [NonAction]
        private void SetSavedSearchEditDropDownList(JobAlertModel model)
        {
            // 职位分类
            //var jobCategorys = _lovService.GetLovByParentLabel("JobCategory").Select(s =>
            //   new { s.Value, s.Name }).AsEnumerable();
            //ViewBag.JobCategorys = new SelectList(jobCategorys, "Value", "Name", Convert.ToString(model.JobType));
            ViewBag.JobCategoryList = _lovService.GetLovList(LovType.JobCategory).ToList();

            //JobCategoryList
            ViewBag.SubJobCategoryList = _lovService.GetSubJobCategoryList().ToList();

            // 绑定行业下拉框
            var industrys = _lovService.GetLovByParentLabel("Industry").Select(s =>
                new { s.Value, s.Name }).AsEnumerable();
            ViewBag.Industrys = new SelectList(industrys, "Value", "Name", Convert.ToString(model.Industry));

            // 绑定学历下拉框
            var educationLevels = _lovService.GetLovByParentLabel("EducationLevel").Select(s =>
                new { s.Value, s.Name }).AsEnumerable();
            ViewBag.EducationLevels = new SelectList(educationLevels, "Value", "Name", model.EducationLevel);

            // 工作经验
            var listYearsOfExperience = _lovService.GetLovByParentLabel("YearsOfExperience").Select(s => new { s.Name, s.Value }).AsEnumerable();
            ViewBag.YearsOfExperiences = new SelectList(listYearsOfExperience, "Value", "Name",
                Convert.ToString(model.YearsOfService));

            // 绑定公司性质下拉框
            var companyTypes = _lovService.GetLovByParentLabel("CompanyType").Select(s =>
                new { s.Value, s.Name }).AsEnumerable();
            ViewBag.CompanyTypes = new SelectList(companyTypes, "Value", "Name", Convert.ToString(model.CompanyType));

            // 目前年薪
            var listSalaryRange = _lovService.GetLovByParentLabel("SalaryRange").Select(s => new { s.Name, s.Value }).AsEnumerable();
            ViewBag.SalaryRanges = new SelectList(listSalaryRange, "Value", "Name", Convert.ToString(model.SalaryRange));

            // 邮件订阅
            var listFrequency = _lovService.GetLovByParentLabel("Frequency").Select(s => new { s.Name, s.Value }).AsEnumerable();
            ViewBag.Frequencys = new SelectList(listFrequency, "Value", "Name", Convert.ToString(model.Frequency));

            // 发送个数
            var listDeliveries = _lovService.GetLovByParentLabel("Deliveries").Select(s => new { s.Name, s.Value }).AsEnumerable();
            ViewBag.Deliveriess = new SelectList(listDeliveries, "Value", "Name", Convert.ToString(model.Deliveries));
        }

        [HttpPost]
        public ActionResult SavedSearchDelete(string deleteId)
        {
            if (!string.IsNullOrWhiteSpace(deleteId))
            {
                var entity = _jobAlertService.GetJobAlertById(Guid.Parse(deleteId));
                _jobAlertService.DeleteJobAlert(entity);
            }
            ViewBag.CurrentAction = "SavedSearchManage";
            return RedirectToAction("SavedSearchManage");
        }

        [HttpPost]
        public ActionResult SavedSearchDeleteList(string deleteIdList)
        {
            var idList = deleteIdList.Split(',').Where(item => !string.IsNullOrWhiteSpace(item));
            foreach (var id in idList)
            {
                var entity = _jobAlertService.GetJobAlertById(Guid.Parse(id));
                _jobAlertService.DeleteJobAlert(entity);
            }
            ViewBag.CurrentAction = "SavedSearchManage";
            return RedirectToAction("SavedSearchManage");
        }
        #endregion

        #region 申请职位
        public ActionResult ApplicationList(PagingFilteringModel command)
        {
            var model = new ApplicationListModel();

            // 设置默认的Page信息
            if (command.PageSize <= 0) command.PageSize = 20;
            if (command.PageNumber <= 0) command.PageNumber = 1;

            var id = _workcontext.CurrentUser.Id;
            var list = _applicationService.GetApplicationsByJobseekerId(id,
                command.PageNumber - 1, command.PageSize);
            model.PagingFilteringContext.LoadPagedList(list);
            model.SearchCount = _applicationService.GetApplicationsByJobseekerId(id).Count();
            model.Applications = list.Select(x =>
            {
                var resumeItem = _resumeService.GetResumeById(x.ResumeId);
                var m = x.ApplicationToModel();                
                m.ResumeName = resumeItem != null ? resumeItem.ResumeName : string.Empty;
                var companyItem = _companyService.GetCompanyById(x.CompanyId);
                m.CompanyName = companyItem != null ? companyItem.CompanyName : string.Empty;

                var jobPosion = _jobPositionService.GetJobPositionById(x.JobPositionId);
                m.JobTitle = jobPosion != null ? jobPosion.JobTitle : string.Empty;
                return m;
            }).ToList();

            return View(model);
        }

        [HttpPost]
        public ActionResult ApplicationDelete(string DeleteIdList)
        {
            var idList = DeleteIdList.Split(',').Where(item => !string.IsNullOrWhiteSpace(item));
            foreach (var id in idList)
            {
                var entity = _applicationService.GetApplicationById(Guid.Parse(id));
                _applicationService.DeleteApplication(entity);
            }
            ViewBag.CurrentAction = "ApplicationList";
            return RedirectToAction("ApplicationList");
        }
        #endregion

        #region 关注职位
        public ActionResult SavedJobList(PagingFilteringModel command)
        {
            var model = new SavedJobListModel();

            // 设置默认的Page信息
            if (command.PageSize <= 0) command.PageSize = 20;
            if (command.PageNumber <= 0) command.PageNumber = 1;

            var id = _workcontext.CurrentUser.Id;
            var list = _savedJobService.GetSavedJobsByJobseekerId(id,
                command.PageNumber - 1, command.PageSize);
            model.PagingFilteringContext.LoadPagedList(list);

            model.SearchCount = _savedJobService.GetSavedJobsByJobseekerId(id).Count();
            model.SavedJobs = list.Select(x =>
            {
                var m = x.SavedJobToModel();
                return m;
            }).ToList();

            return View(model);
        }

        [HttpPost]
        public ActionResult SavedJobDelete(string DeleteId)
        {
            if (!string.IsNullOrWhiteSpace(DeleteId))
            {
                var entity = _savedJobService.GetSavedJobById(Guid.Parse(DeleteId));
                _savedJobService.DeleteSavedJob(entity);
            }
            ViewBag.CurrentAction = "SavedJobList";
            return RedirectToAction("SavedJobList");
        }

        [HttpPost]
        public ActionResult SavedJobDeleteList(string DeleteIdList)
        {
            var idList = DeleteIdList.Split(',').Where(item => !string.IsNullOrWhiteSpace(item));
            foreach (var id in idList)
            {
                var entity = _savedJobService.GetSavedJobById(Guid.Parse(id));
                _savedJobService.DeleteSavedJob(entity);
            }
            ViewBag.CurrentAction = "SavedJobList";
            return RedirectToAction("SavedJobList");
        }
        #endregion

        #region 关注公司
        public ActionResult SavedCompanyList(PagingFilteringModel command)
        {
            var model = new SavedCompanyListModel();

            // 设置默认的Page信息
            if (command.PageSize <= 0) command.PageSize = 20;
            if (command.PageNumber <= 0) command.PageNumber = 1;

            var id = _workcontext.CurrentUser.Id;
            var list = _savedCompanyService.GetSavedCompanysByJobseekerId(id,
                command.PageNumber - 1, command.PageSize);
            model.PagingFilteringContext.LoadPagedList(list);
            model.SearchCount = _savedCompanyService.GetSavedCompanysByJobseekerId(id).Count();
            model.SavedCompanys = list.Select(x =>
            {
                var m = x.SavedCompanyToModel();
                return m;
            }).ToList();

            return View(model);
        }

        [HttpPost]
        public ActionResult SavedCompanyDelete(string DeleteId)
        {
            if (!string.IsNullOrWhiteSpace(DeleteId))
            {
                var entity = _savedCompanyService.GetSavedCompanyById(Guid.Parse(DeleteId));
                _savedCompanyService.DeleteSavedCompany(entity);
            }
            ViewBag.CurrentAction = "SavedCompanyList";
            return RedirectToAction("SavedCompanyList");
        }

        [HttpPost]
        public ActionResult SavedCompanyDeleteList(string DeleteIdList)
        {
            var idList = DeleteIdList.Split(',').Where(item => !string.IsNullOrWhiteSpace(item));
            foreach (var id in idList)
            {
                var entity = _savedCompanyService.GetSavedCompanyById(Guid.Parse(id));
                _savedCompanyService.DeleteSavedCompany(entity);
            }
            ViewBag.CurrentAction = "SavedCompanyList";
            return RedirectToAction("SavedCompanyList");
        }
        #endregion

        #region 公司来信
        public ActionResult Inbox(PagingFilteringModel command)
        {
            // 设置默认的Page信息
            if (command.PageSize <= 0) command.PageSize = 20;
            if (command.PageNumber <= 0) command.PageNumber = 1;

            var id = _workcontext.CurrentUser.Id;
            var list = _receivedMessageService.GetReceivedMessagesByJobseekerId(id);

            var searchList = list.Select(s => new InboxModel()
            {
                Subject = s.Subject,
                Body = s.Body,
                DateReceived = s.DateReceived,
                DateSent = s.DateSent,
                Flag = s.Flag,
                From = s.From,
                Id = s.Id,
                To = s.To                
            }).ToList();
            searchList.ForEach(s =>
            {       
                var from = _companyService.GetCompanyById(s.From);
                if (from != null)
                {
                    s.FromName = from.CompanyName;
                    s.FromType = from.CompanyType.HasValue ? _lovService.GetLovName(from.CompanyType.Value) : string.Empty;
                    s.IndustryName = from.Industry.HasValue ? _lovService.GetLovName(from.Industry.Value) : string.Empty;
                }
                else
                {
                    s.FromName = string.Empty;
                }
            });
            var model = new InboxListModel()
            {
                JobAlertList = new PagedList<InboxModel>(searchList, command.PageNumber - 1, _pageSize),
                SearchCount = list.Count(),
                PagingFilteringContext = new PagingFilteringModel()
            };
            model.PagingFilteringContext.LoadPagedList(model.JobAlertList);
            return View(model);
        }

        [HttpPost]
        public ActionResult InboxDeleteList(string DeleteIdList)
        {
            var idList = DeleteIdList.Split(',').Where(item => !string.IsNullOrWhiteSpace(item));
            foreach (var id in idList)
            {
                var entity = _receivedMessageService.GetReceivedMessageById(Guid.Parse(id));
                _receivedMessageService.DeleteReceivedMessage(entity);
            }
            ViewBag.CurrentAction = "Inbox";
            return RedirectToAction("Inbox");
        }
        #endregion

        /// <summary>
        /// 导航菜单
        /// </summary>
        /// <returns></returns>
        public PartialViewResult Navigation(String currentAction)
        {
            ViewBag.CurrentAction = currentAction;
            return PartialView();
        }
    }
}
